/*
 *
 *
 *
 */
package com.hboxs.asl.controller.app.product;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created by xxx on 2016/11/25.
 * Controller - 购物车
 */
@Controller("appCartController")
@RequestMapping("/app/m/cart")
public class CartController extends BaseController {

    protected Logger logger = Logger.getLogger(getClass().getName());
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "cartItemServiceImpl")
    private CartItemService cartItemService;
    @Resource(name = "promotionServiceImpl")
    private PromotionService promotionService;


    /**
     * 添加(app:未登录需要id和key,登录需要token)
     *
     * @param productId 产品id
     * @param quantity  产品数量
     * @param anchorId  主播id
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    Object add(Long productId, Integer quantity, Long anchorId) {
        try {
            synchronized (String.valueOf(memberService.getCurrentByToken()).intern()) {

                if (quantity == null || quantity < 1) {
                    return JsonMessage.error("商品数量必须为正整数");
                }
                Product product = productService.find(productId);
                if (product == null) {
                    return JsonMessage.error("找不到该商品");
                }
                if (!product.getIsMarketable()) {
                    return JsonMessage.error("该商品已下架");
                }

                Cart cart = cartService.getCurrentByToken(memberService.getCurrentByToken());

                if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
                    return JsonMessage.error("最多允许添加" + Cart.MAX_PRODUCT_COUNT + "种商品至购物车");
                }

                if (cart.contains(product)) {
                    CartItem cartItem = cart.getCartItem(product);
                    if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
                        return JsonMessage.error("商品数量不允许超过" + CartItem.MAX_QUANTITY);
                    }
                    if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
                        return JsonMessage.error("该商品库存不足");
                    }
                    // 设置主播
                    if (anchorId != null) {
                        cartItem.setAnchor(memberService.find(anchorId));
                    }
                    cartItemService.add(cartItem, quantity);
                } else {
                    if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
                        return JsonMessage.error("商品数量不允许超过" + CartItem.MAX_QUANTITY);
                    }
                    if (product.getStock() != null && quantity > product.getAvailableStock()) {
                        return JsonMessage.error("该商品库存不足!");
                    }
                    cartItemService.create(product, quantity, cart, null, anchorId);
                }
                return JsonMessage.success();

            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 购物车详情(app:未登录需要id和key,登录需要token)
     *
     * @return Object
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    Object list() {
        try {

            Cart cart = cartService.getCurrentByToken();

            if (cart == null || cart.isEmpty()) {
                return JsonMessage.success();
            }

            cartService.dealPromotion(cart);

            // 推荐促销
            List<Promotion> ps = promotionService.findListNotInCart(cart);


            return JsonMessage.success(
                    "cart",
                    JsonMessage.optimiseObj(
                            cart,
                            "effectivePrice", "quantity", "weight"

                    ),
                    "cartItems", cartService.splitCart(cart),

                    "promotions",
                    JsonMessage.optimiseObj(
                            ps, "id", "type", "title"
                    )

            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 获取促销商品推荐(app:未登录需要id和key,登录需要token)
     *
     * @return Object
     */
    @RequestMapping(value = "/promotion-list", method = RequestMethod.GET)
    public
    @ResponseBody
    Object promotionList(Long promotionId) {
        try {

            Cart cart = cartService.getCurrentByToken();

            if (cart == null || cart.isEmpty()) {
                return JsonMessage.success();
            }

            Promotion promotion = promotionService.find(promotionId);
            if (promotion == null) {
                return JsonMessage.success();
            }


            Set<Product> products = promotionService.findProductByPromotion(promotion, cart);
            return JsonMessage.success(
                    "products", JsonMessage.optimiseObj(
                            products, "id", "image", "name", "price", "promotionPrice", "finalScore", "weight", "sales"
                    )

            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 编辑(app:未登录需要id和key,登录需要token)
     *
     * @param quantity 商品数量
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    Object edit(Long cartItemId, Integer quantity) {
        try {
            if (quantity == null || quantity < 1) {
                return JsonMessage.error("商品数量必须为正整数!");
            }
            Cart cart = cartService.getCurrentByToken();
            if (cart == null || cart.isEmpty()) {
                return JsonMessage.error("购物车不能为空!");
            }
            CartItem cartItem = cartItemService.find(cartItemId);
            Set<CartItem> cartItems = cart.getCartItems();

            if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
                return JsonMessage.error("购物车项不存在");
            }
            if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
                return JsonMessage.error("商品数量不允许超过" + CartItem.MAX_QUANTITY);
            }
            Product product = cartItem.getProduct();
            if (product.getStock() != null && quantity > product.getAvailableStock()) {
                return JsonMessage.error("该商品库存不足");
            }
            cartItem.setQuantity(quantity);
            cartItemService.update(cartItem);

            return JsonMessage.success(

                    "cart", JsonMessage.optimiseObj(cart, "effectivePrice")

                    , "cartItem", JsonMessage.optimiseObj(cartItem, "subtotal", "point", "quantity")
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 删除(app:未登录需要id和key,登录需要token)
     *
     * @param cartItemId 购物项Id
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Object delete(Long cartItemId) {

        try {
            Cart cart = cartService.getCurrentByToken();
            if (cart == null || cart.isEmpty()) {
                return JsonMessage.error("购物车不能为空");
            }
            CartItem cartItem = cartItemService.find(cartItemId);
            Set<CartItem> cartItems = cart.getCartItems();
            if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
                return JsonMessage.error("购物车项不存在");
            }
            cartItems.remove(cartItem);
            cartItemService.delete(cartItem);
            return JsonMessage.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 修改购物车选择标记
     */
    @RequestMapping(value = "/selected", method = RequestMethod.POST)
    public
    @ResponseBody
    Object changeSelectedStatus(Long cartItemId, Boolean isSelected) {

        try {
            CartItem cartItem = cartItemService.find(cartItemId);
            if (cartItem == null && isSelected == null) {
                return JsonMessage.error("购物项参数错误");
            }
            cartItemService.changeSelectedStatus(cartItem, isSelected);
            return JsonMessage.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 立即购买
     *
     * @param productId 商品id
     * @param quantity  商品数量
     * @param anchorId  主播id
     * @return json
     */
    @RequestMapping(value = "/buy_now", method = RequestMethod.POST)
    public
    @ResponseBody
    Object buy_now(Long productId, Integer quantity, Long anchorId) {

        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Product product = productService.find(productId);
            if (product == null) {
                return JsonMessage.error("找不到该商品");
            }
            Cart cart = cartService.getCurrentByToken(memberService.getCurrentByToken());

            if (cart != null) {
                if (cart.contains(product)) {
                    this.delete(cart.getCartItem(product).getId());
                }
                cartService.cancelSelected(cart);
            }
            return this.add(productId, quantity, anchorId);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 全选购物车项
     */
    @RequestMapping(value = "/selected_all", method = RequestMethod.GET)
    public
    @ResponseBody
    Object selected_all() {

        try {
            Cart cart = cartService.getCurrentByToken();
            if (cart == null) {
                return JsonMessage.error("购物车不能为空");
            }
            Set<CartItem> cartItems = cart.getCartItems();
            if (cartItems.size() == 0) {
                return JsonMessage.error("购物车不能为空");
            }
            cartService.selectedAll(cart);

            return JsonMessage.success();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
